/**
 * @program: LeetCode
 * @description: LeetCode : 37. 解数独
 * @author: WXY
 * @create: 2023-01-20 09:29
 * @Version 1.0
 **/
public class Num037_solveSudoku {
    public static void solveSudoku(char[][] board) {
        process(board);
    }

    private static boolean process(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] != '.')continue;
                for (int k = 0; k < 9; k++) {
                    if (isValid(i, j, (char) k,board)) {
                        board[i][j] = (char) k;
                        if (process(board)) return true;
                        board[i][j] = '.';
                    }
                }
                return false;
            }
        }
        return true;
    }

    private static boolean isValid(int row, int col, char val, char[][] board) {
        for (int i = 0; i < 9; i++) {
            if (board[row][i] == val) {
                return false;
            }
        }
        for (int i = 0; i < 9; i++) {
            if (board[i][col] == val) {
                return false;
            }
        }
        int startRow = (row / 3) * 3;
        int startCol = (col / 3) * 3;
        for (int i = startRow; i < startRow + 3; i++) {
            for (int j = startCol; j < startCol + 3; j++) {
                if (board[i][j] == val) {
                    return false;
                }
            }
        }
        return true;
    }
}
